package edu.whu.notepal.controller;


import edu.whu.notepal.dto.Result;
import edu.whu.notepal.pojo.Column;
import edu.whu.notepal.service.ColumnService;
import edu.whu.notepal.utils.RedisClient;
import edu.whu.notepal.utils.RedisConstants;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * @description 栏目的相关接口，使用Redis进行缓存
 * @author 陈磊
 */
@RestController
@RequestMapping("/column")
public class ColumnController {

    @Resource
    ColumnService columnService;

    @Resource
    RedisClient redisClient;


    /**
     * 获取所有栏目
     * @return
     */
    @GetMapping
    public Result<List<Column>> getAll(){
        String key = RedisConstants.COLUMN_INFO_KEY+"all";
        if(redisClient.hasKey(key)){
            List<Column> list = redisClient.getList(key, 0, -1, Column.class);
            return Result.success(list);
        }
        List<Column> list = columnService.list();
        redisClient.saveList(key,list,RedisConstants.COLUMN_INFO_TTL, TimeUnit.HOURS);
        return Result.success(list);
    }

    @PutMapping
    public Result<String> update(@RequestBody Column column){
        redisClient.deleteKey(RedisConstants.COLUMN_INFO_KEY+column.getId());
        redisClient.deleteKey(RedisConstants.COLUMN_INFO_KEY+"all");
        columnService.updateById(column);
        return Result.success("成功修改");
    }

    @PostMapping
    private Result<String> save(@RequestBody Column column){
        redisClient.deleteKey(RedisConstants.COLUMN_INFO_KEY+"all");
        Long count = Integer.toUnsignedLong(columnService.count());
        column.setId(count);
        columnService.save(column);
        return Result.success("保存成功");
    }

    @DeleteMapping("/{id}")
    private Result<String> delete(@PathVariable("id")Long id){
        redisClient.deleteKey(RedisConstants.COLUMN_INFO_KEY+id);
        redisClient.deleteKey(RedisConstants.COLUMN_INFO_KEY+"all");
        columnService.removeById(id);
        return Result.success("成功删除");
    }

    @GetMapping("/{id}")
    private Result<Column> getById(@PathVariable("id")Long id){
        Column column = redisClient.queryWithPassThrough(RedisConstants.COLUMN_INFO_KEY, id,
                Column.class, columnService::getById, RedisConstants.COLUMN_INFO_TTL, TimeUnit.HOURS);
        return Result.success(column);
    }

}